package com.rongxun.hbwallet.ui.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.rongxun.base.BaseActivity;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.IntentKey;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.hbwallet.jsinterface.JsInteration;
import com.rongxun.hbwallet.model.bean.H5UserInfo;
import com.rongxun.hbwallet.model.bean.User;
import com.rongxun.utils.ActivityUtils;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.JsonUtils;
import com.rongxun.utils.PreferenceUtils;
import com.rongxun.utils.StatusBarUtil;

import butterknife.BindView;
import butterknife.OnClick;
import wendu.webviewjavascriptbridge.WVJBWebView;

/**
 * 创建者     庄丰泽
 * 创建时间   2018/6/7 14:05
 * 描述	      WebView
 */

public class WebActivity extends BaseActivity implements View.OnKeyListener {
    @BindView(R.id.toolbar_title)
    TextView    mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar     mToolbar;
    @BindView(R.id.web_wv)
    WVJBWebView mWebView;

    @BindView(R.id.web_prb)
    ProgressBar mProgress;

    String url = "";
    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.clearFormData();
            mWebView.destroy();
        }

    }

    @Override
    protected void init() {
        StatusBarUtil.setToolBarPaddingTop(mToolbar, this);
        mToolbarBack.setVisibility(View.VISIBLE);
        url = getIntent().getStringExtra(IntentKey.WEB_URL);
        initWebView();
        if (url.startsWith(HttpConstants.WEB_ADDRESS.ETH_TRANSACTIONS_URL)) {
            mToolbarTitle.setText(getString(R.string.transaction_list));
        } else if (url.startsWith(HttpConstants.WEB_ADDRESS.ETH_TRANSACTIONS_DETAIL_URL)) {
            mToolbarTitle.setText(getString(R.string.transaction_detail));
        }
    }

    private void initWebView() {
        // 得到setting
        WebSettings settings = mWebView.getSettings();

        //支持的语言类型
        settings.setDefaultTextEncodingName("UTF-8");
        //设置可以访问文件
        settings.setAllowFileAccess(true);

        settings.setDomStorageEnabled(true);

        settings.setJavaScriptEnabled(true);//设置JS可用

        JsInteration jsInteration = new JsInteration(this, mToolbarTitle);

        mWebView.addJavascriptInterface(jsInteration, "control");//传递对象进行交互

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setTextZoom(100);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setLoadWithOverviewMode(true);

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                FlyLog.i("url" + url);
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (mProgress != null)
                    mProgress.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (mProgress != null) {
                    mProgress.setVisibility(View.GONE);
                }
                super.onPageFinished(view, url);
            }
        });


        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //                mToolbarTitle.setText(title);
            }

            //加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (mProgress != null)
                    mProgress.setProgress(newProgress);

            }


            @Override
            public void onRequestFocus(WebView view) {
                super.onRequestFocus(view);
            }
        });
        mWebView.setOnKeyListener(this);
        mWebView.loadUrl(url);

        mWebView.registerHandler("setNativeTitle", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->
                mToolbarTitle.setText(s));

        mWebView.registerHandler("getNativeUserInfo", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->

                wvjbResponseCallback.onResult(getUserInfo()));

        mWebView.registerHandler("tokenExpired", (WVJBWebView.WVJBHandler<String, String>) (s, wvjbResponseCallback) ->

                ActivityUtils.startActivityWithAnimotionBottomToTop(WebActivity.this, new Intent(WebActivity.this, LoginActivity.class)));
    }

    private void getShareContent(@NonNull WVJBWebView webView) {
        webView.callHandler("shareContent", (WVJBWebView.WVJBResponseCallback<String>) data ->

                Toast.makeText(WebActivity.this, data, Toast.LENGTH_SHORT).show());

    }

    private void callEvaluateJavascript(@NonNull WVJBWebView webView) {
        String toJson = getUserInfo();

        webView.callHandler("setH5UserInfo", toJson, (WVJBWebView.WVJBResponseCallback<String>) data -> {

        });
    }

    private String getUserInfo() {
        H5UserInfo h5UserInfo = new H5UserInfo();
        h5UserInfo.setToken(PreferenceUtils.getString(SPKey.TOKEN, ""));

        String userJson = PreferenceUtils.getString(SPKey.USER, "");

        User user = JsonUtils.fromJson(userJson, User.class);

        h5UserInfo.setUser(user);

        String toJson = JsonUtils.toJson(h5UserInfo);

        FlyLog.i("toJson" + toJson);
        return toJson;
    }

    @Override
    protected int getContentView() {

        return R.layout.activity_web;

    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            if (mWebView != null) {
                mWebView.goBack();
            }
            return true;
        }

        return false;
    }

    @OnClick(R.id.toolbar_back)
    public void onViewClicked() {
        onBackPressed();
    }
}
